//创建用户相关的小仓库
import { defineStore } from "pinia";
import { WebSocketMsg } from '@/utils/websocket';
import tradeApi from '@/api/trade';

//创建小仓库  选择式API
let useQuoteStore = defineStore('quote', {
    //存储数据state
    state: () => {
        return {
            bestQuoteList: [] as any[],
            bestQuoteReceiveStatus: false,
            bestQuoteListTemp: [] as any[],
            conditionData: {} as any,
        }
    },
    actions: {
        async getQuoteList(data:any,nowParam:any){
            this.bestQuoteReceiveStatus =  true;
            this.conditionData = data;
            tradeApi.getObbList(nowParam).then((res: any) => {
                this.bestQuoteReceiveStatus =  false;
                this.bestQuoteList = res.results?res.results:[];                 
                this.bestQuoteList.forEach((item:any)=>{
                    item.dictQuoteSourceType = item.dictQuoteSourceTypeBid?item.dictQuoteSourceTypeBid:item.dictQuoteSourceTypeOfr;
                })
            }).catch((err:any) => {
                console.log(err);
                this.bestQuoteReceiveStatus =  false;
            });          
        },
        filterQuoteItem(_item:any){
            return true;
            // if(!item.condition){
            //     return
            // }
            // let dateStart = this.conditionData.endDateLowerLimit ? new Date(Date.parse(this.conditionData.endDateLowerLimit.replace(/-/g,"/"))) : null; //格式yyyy-MM-dd转换成yyyy/MM/dd
            // let dateEnd= this.conditionData.endDateUpLimit ? new Date(Date.parse(this.conditionData.endDateUpLimit.replace(/-/g,"/"))): null;
            // let myDate=null;
            // let isSearchKey = false;
            // let searchStr = '';
            // let isDictTimeOption = false;
            // let isDictPriceType = false;
            // let myYielcCb = null;
            // let myNetPriceCb = null;
            // let myBid: number | null = null;
            // let myOfr = null;
            // let myBestQuoteType = false;
            
            // searchStr = item.condition.bondCode +'_'+item.condition.bondName+'_'+item.condition.bondFullName+item.condition.issuerName;
            // isSearchKey = !this.conditionData.searchKey||(this.conditionData.searchKey&& searchStr.indexOf(this.conditionData.searchKey)!= -1);
            
            // isDictTimeOption = !this.conditionData.dictTimeOption||
            //     (this.conditionData.dictTimeOption==1 && (!this.conditionData.termDayUpLimit||(this.conditionData.termDayUpLimit&&(this.conditionData.termDayUpLimit>item.condition.leftTermYear||this.conditionData.termDayUpLimit===item.condition.leftTermYear))) && (!this.conditionData.termDayLowerLimit|| (this.conditionData.termDayLowerLimit&&(this.conditionData.termDayLowerLimit<item.condition.leftTermYear||this.conditionData.termDayLowerLimit===item.condition.leftTermYear))))||
            //     (this.conditionData.dictTimeOption==2 && (!this.conditionData.termDayUpLimit||(this.conditionData.termDayUpLimit&& (this.conditionData.termDayUpLimit>item.condition.leftTermMonth||this.conditionData.termDayUpLimit===item.condition.leftTermMonth))) && (!this.conditionData.termDayLowerLimit|| (this.conditionData.termDayLowerLimit&&(this.conditionData.termDayLowerLimit<item.condition.leftTermMonth||this.conditionData.termDayLowerLimit===item.condition.leftTermMonth)))) || 
            //     (this.conditionData.dictTimeOption==3 && (!this.conditionData.termDayUpLimit||(this.conditionData.termDayUpLimit&&(this.conditionData.termDayUpLimit>item.condition.leftTermDay||this.conditionData.termDayUpLimit===item.condition.leftTermDay))) && (!this.conditionData.termDayLowerLimit|| (this.conditionData.termDayLowerLimit&&(this.conditionData.termDayLowerLimit<item.condition.leftTermDay||this.conditionData.termDayLowerLimit===item.condition.leftTermDay))));
            // // dictPriceType=1收益率（判断估值是否在区间priceLowerLimit、priceUpLimit,优先考虑行权）
            // // dictPriceType=2净价（判断净价）
            // myYielcCb = item.condition.yieldCbExer?item.condition.yieldCbExer:item.condition.yieldCb;
            // myNetPriceCb = item.condition.netPriceCbExer?item.condition.netPriceCbExer:item.condition.netPriceCb;
            // if (item.value.priceBid&&item.value.priceBid !== 'Bid') {
            //     myBid = parseFloat(item.value.priceBid);
            // }
            // if(item.value.priceOfr&&item.value.priceOfr =='Ofr'){
            //     myOfr = parseFloat(item.value.priceOfr);
            // }
            // isDictPriceType =  !this.conditionData.dictPriceType||
            //     (this.conditionData.dictPriceType==1&&(
            //         ((!this.conditionData.priceUpLimit||(this.conditionData.priceUpLimit&&myBid&&(this.conditionData.priceUpLimit>myBid||this.conditionData.priceUpLimit===myBid)))&&(!this.conditionData.priceLowerLimit||(this.conditionData.priceLowerLimit&&myBid&&(this.conditionData.priceLowerLimit<myBid||this.conditionData.priceLowerLimit===myBid))))||
            //         ((!this.conditionData.priceUpLimit||(this.conditionData.priceUpLimit&&myOfr&&(this.conditionData.priceUpLimit>myOfr||this.conditionData.priceUpLimit===myOfr)))&&(!this.conditionData.priceLowerLimit||(this.conditionData.priceLowerLimit&&myOfr&&(this.conditionData.priceLowerLimit<myOfr||this.conditionData.priceLowerLimit===myOfr)))) ||
            //         ((!this.conditionData.priceUpLimit||(this.conditionData.priceUpLimit&&(this.conditionData.priceUpLimit>myYielcCb||this.conditionData.priceUpLimit===myYielcCb)))&&(!this.conditionData.priceLowerLimit||(this.conditionData.priceLowerLimit&&(this.conditionData.priceLowerLimit<myYielcCb||this.conditionData.priceLowerLimit===myYielcCb))))
            //     ))||
            //     (this.conditionData.dictPriceType==2&&(!this.conditionData.priceUpLimit||(this.conditionData.priceUpLimit&&(this.conditionData.priceUpLimit>myNetPriceCb||this.conditionData.priceUpLimit===myNetPriceCb)))&&
            //         (!this.conditionData.priceLowerLimit||(this.conditionData.priceLowerLimit&&(this.conditionData.priceLowerLimit<myNetPriceCb||this.conditionData.priceLowerLimit===myNetPriceCb)))
            //     ); 
            // myDate = item.condition.endDate;
            // myDate = myDate.substring(0,4) + '/'+ myDate.substring(4,6)+ '/' + myDate.substring(6,8);
            // myDate = new Date(Date.parse(myDate));
            // myBestQuoteType = true

            // if( isSearchKey &&
            //     (!this.conditionData.dictQuoteDirect||!item.condition.dictQuoteDirect||(this.conditionData.dictQuoteDirect&&this.conditionData.dictQuoteDirect==item.condition.dictQuoteDirect)) &&
            //     isDictPriceType &&
            //     (!this.conditionData.dictQuoteBestBondType||(this.conditionData.dictQuoteBestBondType&&idsToArr(this.conditionData.dictQuoteBestBondType).includes(item.condition.dictQuoteBestBondType))) &&
            //     (!this.conditionData.dictQuoteBestLeftTerm||(this.conditionData.dictQuoteBestLeftTerm&&idsToArr(this.conditionData.dictQuoteBestLeftTerm).includes(item.condition.dictQuoteBestLeftTerm))) &&
            //     isDictTimeOption &&
            //     (!this.conditionData.rateUpLimit||(this.conditionData.rateUpLimit&& (this.conditionData.rateUpLimit>item.condition.rate || this.conditionData.rateUpLimit===item.condition.rate))) &&
            //     (!this.conditionData.rateLowerLimit|| (this.conditionData.rateLowerLimit&& (this.conditionData.rateLowerLimit<item.condition.rate||this.conditionData.rateLowerLimit===item.condition.rate))) &&
            //     this.isEqual(this.conditionData.isForever,item.condition.isForever)&&
            //     this.isEqual(this.conditionData.isCityInvest,item.condition.isCityInvest) &&
            //     (!this.conditionData.dictQuoteBestIssuerRating||(this.conditionData.dictQuoteBestIssuerRating&&idsToArr(this.conditionData.dictQuoteBestIssuerRating).includes(item.condition.dictQuoteBestIssuerRating))) &&
            //     (!this.conditionData.dictQuoteBestBondRating||(this.conditionData.dictQuoteBestBondRating&&idsToArr(this.conditionData.dictQuoteBestBondRating).includes(item.condition.dictQuoteBestBondRating))) &&
            //     this.isEqual(this.conditionData.isCountry,item.condition.isCountry)&&
            //     (this.conditionData.dictCrIndustryMode.length==0|| this.conditionData.dictCrIndustryMode.includes(item.condition.dictCrIndustryMode)) &&
            //     (this.conditionData.forProvinceId.length==0|| this.conditionData.forProvinceId.includes(item.condition.forProvinceId)) &&
            //     this.isEqual(this.conditionData.isCumRights,item.condition.isCumRights) &&
            //     (!this.conditionData.dictCirculationMarket||(this.conditionData.dictCirculationMarket&&idsToArr(this.conditionData.dictCirculationMarket).includes(item.condition.dictCirculationMarket)))&&
            //     // 到期日
            //     (!this.conditionData.endDateUpLimit||(this.conditionData.endDateUpLimit&&dateEnd&&(dateEnd>myDate||dateEnd==myDate)))&&
            //     (!this.conditionData.endDateLowerLimit||(this.conditionData.endDateLowerLimit&&dateStart&&(dateStart<myDate||dateStart==myDate)))&&
            //     this.isEqual(this.conditionData.isOpen,item.condition.isOpen) &&
            //     this.isEqual(this.conditionData.isPledged,item.condition.isPledged) &&
            //     this.isEqual(this.conditionData.isAssure,item.condition.isAssure) && myBestQuoteType
            // ){
            //     return true;
            // }
        },
        isEqual (str: any,num: { toString: () => any; } | null){
            if(!str){
                return true
            }else if(num != null && str == num.toString()){
                return true
            }else{
                return false
            }
        },
        //获取websocket最新行情
        addQuote(quoteData: WebSocketMsg) {
            console.log('推送：', quoteData.Data);   
            quoteData.Data.value.dictQuoteSourceType = quoteData.Data.value.dictQuoteSourceTypeBid?quoteData.Data.value.dictQuoteSourceTypeBid:quoteData.Data.value.dictQuoteSourceTypeOfr;
            if (!this.bestQuoteReceiveStatus) {
                this.bestQuoteListTemp.push(quoteData.Data.value);
            }else{
                //1、当bestQuoteListTemp不为空数组时，需要对数组进行合并处理
                if(this.bestQuoteListTemp.length > 0){
                    // 创建一个映射表，用于快速查找 bestQuoteList 中的元素
                    const bestQuoteMap = new Map(this.bestQuoteList.map(item => [item.quoteUniCode, item]));

                    this.bestQuoteListTemp.forEach(tempItem => {
                        const existingItem = bestQuoteMap.get(tempItem.quoteUniCode);
                        if (existingItem) {
                            // 检查 uniCode 是否需要更新
                            if (tempItem.uniCode > existingItem.uniCode) {
                                // 移除旧的项
                                const index = this.bestQuoteList.findIndex(item => item.quoteUniCode === tempItem.quoteUniCode);
                                this.bestQuoteList.splice(index, 1);
                                // 从映射表中也移除
                                bestQuoteMap.delete(tempItem.quoteUniCode);
                                // 插入新的项到数组开头
                                if (this.filterQuoteItem(tempItem)){
                                    this.bestQuoteList.unshift(tempItem);
                                }                                
                                // 更新映射表
                                bestQuoteMap.set(tempItem.quoteUniCode, tempItem);
                            }
                        } else {
                            // 如果 bestQuoteList 中没有找到对应的 quoteUniCode，直接插入到开头
                            if (this.filterQuoteItem(tempItem)){
                                this.bestQuoteList.unshift(tempItem);
                            }                              
                            // 更新映射表
                            bestQuoteMap.set(tempItem.quoteUniCode, tempItem);
                        }
                    });
                    this.bestQuoteListTemp.length=0;
                    if (this.bestQuoteList.length > 100) {
                        // 超过时，移除最后100之后的数据
                        this.bestQuoteList.splice(-1, this.bestQuoteList.length - 100);
                    }
                }else{
                    const index = this.bestQuoteList.findIndex(item => item.quoteUniCode === quoteData.Data.value.quoteUniCode);
                    if (index >= 0){
                        this.bestQuoteList.splice(index, 1);
                    }
                    if (this.filterQuoteItem(quoteData.Data.value)){
                        this.bestQuoteList.unshift(quoteData.Data.value);
                    }                      
                    // 确保xBondQuoteList的长度不超过100
                    if (this.bestQuoteList.length > 100) {
                        // 超过时，移除最后一个元素（最旧的行情）
                        this.bestQuoteList.pop();
                    }
                }
            }            
        },
    },
    getters: {
    }
})

export default useQuoteStore;
// function getQuoteList(data: any, nowParam: any) {
//     throw new Error("Function not implemented.");
// }

